package com.zzl.car.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

public class ZdpMailUtil {
    //smtp服务器
    private static String myEmailSMTPHost = "smtp.qq.com";

    //发件人
    private static String myEmailAccount = "499799703@qq.com";
    //授权码
    private static String myEmailPassword = "yahblruxemaebgfg";
    /*
    * 发送邮件
    * */
    public static void sendMessage(String toEmailAddress,String emailTitle,String emailContent) throws GeneralSecurityException, MessagingException {
        //存放配置信息
        Properties prop = new Properties();
        prop.setProperty("mail.host",myEmailSMTPHost);///设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
        prop.put("mail.smtp.port",465);
        // 开启debug调试
        prop.setProperty("mail.debug", "true");
        /**SSL认证，注意腾讯邮箱是基于SSL加密的，所以需要开启才可以使用**/
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        //设置是否使用ssl安全连接（一般都使用）
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session对象
        Session session = Session.getDefaultInstance(prop);
        //获取信封
        Message msg = new MimeMessage(session);
        //写入内容
        msg.setSubject(emailTitle);
        msg.setContent(emailContent,"text/html;charset=utf-8");
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(myEmailAccount));
        msg.setRecipient(Message.RecipientType.TO,new InternetAddress(toEmailAddress));
        //获取到邮差
        Transport transport = session.getTransport();
        //连接邮件服务器
        transport.connect(myEmailSMTPHost,myEmailAccount,myEmailPassword);
        //发送邮件
        transport.sendMessage(msg,msg.getAllRecipients());
    }
}
